/* Z.lib ,ImageBrowser,gudaojuanma.com */

(function(window){
	function ImageBrowser(target,type){
		var self = this;

		this.target = target;
		this.type = type || ImageBrowser.SINGLE;

		this.images = [];
		this.image = null;
		this.ajaxLoader = null;
		this.dialog = null;
		this.parent = 0;

		switch(this.type){
			case ImageBrowser.MULTIPLE:
				this.title = '选择多个图片（按ctrl键加选）';
				this.handle = $('<div class="z-image-browser-handle"><div class="multiple"><table cellpadding="0"><tbody><tr><td></td></tr></tbody></table></div></div>');
				break;
			case ImageBrowser.SINGLE:
				this.title = '选择单个图片';
				this.handle = $('<div class="z-image-browser-handle"><div class="single"></div></div>');
				break;
		}

		this.templates = {
			'main' : '<div class="z-image-browser">\
						<form action="/node/records" method="get" class="filter">\
							<span class="label">名称</span>\
							<input type="text" class="text" name="name" style="width: 120px;"/>\
							<span class="label">上传时间</span>\
							从 <input type="text" class="text datetime" name="start" autocomplete="off"/>\
							到 <input type="text" class="text datetime" name="end" autocomplete="off"/>\
							<input type="submit" class="submit" name="submit" value="检索"/>\
						</form>\
						<ul class="parents"><li><a href="javascript:void(0);" data="0">Top</a></li></ul>\
						<ul class="records"><li>Loading...</li></ul>\
						<div class="pagination"></div>\
						<ul class="button">\
							<li><a href="javascript:void(0);" class="submit">确定</a></li>\
							<!--<li><a href="javascript:void(0);" class="add-image">添加图片</a></li>-->\
						</ul>\
						<div class="clear"></div>\
					</div>',
			'uploadForm' : '<form action="${Z.url("/image/insert")}" method="post" enctype="multipart/form-data" target="submit-target">\
								<input type="hidden" name="parent" value="${parent}"/>\
								<input type="hidden" name="callback" value="${callback}"/>\
								<div class="form-row">\
									<label for="label">名称</label>\
									<input type="text" class="text" name="label"/>\
								</div>\
								<div class="form-row">\
									<label for="sizes">缩略图尺寸</label>\
									<input type="text" class="text" name="sizes" value="${sizes}" style="width:300px;"/>\
								</div>\
								<div class="form-row">\
									<label for="file">图片</label>\
									<input type="file" name="file" />\
								</div>\
								<div class="form-button">\
									<input type="submit" name="submit" value="上传"/>\
								</div>\
								<iframe name="submit-target" style="widht:0;height:0;display:none;"></iframe>\
							</form>',
			'list' : '<li data="${id}" title="${label}" type="${type}">\
							<a href="javascript:void(0);">\
								{{if type==1}}<span class="image-container"><img src="'+Z.url('/assets/img/folder.png')+'" alt="${label}"/></span>{{/if}}\
								{{if type==2}}<span class="image-container"><img src="${$item.thumbnail(name)}" alt="${label}"/></span>{{/if}}\
								<span class="label">${$item.substr(label,10)}</span><span class="created_at">${created_at}</span>\
							</a>\
						</li>'
		};

		$(target).hide();

		this.handle.insertAfter(target);

		this.init();

		this.handle.click(function(){
			self.open();
			return false;
		});
	}

	ImageBrowser.MULTIPLE = 1;

	ImageBrowser.SINGLE = 2;

	ImageBrowser.uploadDialog = null;

	ImageBrowser.uploadBack = function(status,msg,data){
		Z.uploadBack(status, msg, data, function(){
			ImageBrowser.uploadDialog.close();
		});
	};

	ImageBrowser.prototype = {
		'init' : function(){
			var self = this,
			val = $(this.target).val();

			if(val == ''){
				return;
			}

			switch(this.type){
				case ImageBrowser.SINGLE:
					if(Z.parseInt(val) > 0){
						Z.ajax({
							url : Z.url('/backend/node/records'),
							data : {
								id : Z.parseInt(val),
								parent: -1
							},
							success : function(data){
								if(data.total > 0){
									var src = Z.url('/assets/upload/img/'+Z.thumbnailName(data.records[0].name, '150_150')),
									alt = data.records[0].label;
									$(self.target).next('div.z-image-browser-handle').children('div').html('<img src="'+src+'" alt="'+alt+'" onload="window.alignImage(this,150,150);"/>');
								}
							}
						});
					}
					break;
				case ImageBrowser.MULTIPLE:
					var ids = val.split(',');
					if(ids.length > 0){
						Z.ajax({
							url : Z.url('/backend/node/records'),
							data : {
								ids : val,
								order_type : 1,
								parent: -1
							},
							success : function(data){
								if(data.total > 0){
									var tds = [];
									$(data.records).each(function(i,item){
										var src = Z.url('/assets/upload/img/'+Z.thumbnailName(item.name, '150_150')),
										alt = data.records[0].label;
										tds.push('<td><div><img src="'+src+'" alt="'+alt+'"/><a href="javascript:void(0);" data="'+item.id+'">X</a></div></td>');
									});
									$(self.target).next('div').find('tr').html(tds.join(''));
									$(self.target).next().find('td > div > a').click(function(){
										var valArray = $(self.target).val().split(','),
										id = $(this).attr('data'),
										index = $.inArray(id,valArray);

										$(self.target).val(valArray.del(index).join(','));
										$(this).parent().remove();
										return false;
									});
								}
							}
						});
					}
					break;
			}
		},
		'open' : function(dialog){
			var self = this;

			Z.alert({
				'title' : this.title,
				'width' : 658,
				'content' : this.templates.main,
				'open' : function(dialog){
					self.dialog = dialog;

					$('input.datetime').datepicker({
						'dateFormat' : 'yy-mm-dd',
						'monthNames' : ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
						'dayNames'   : ['周一','周二','周三','周四','周五','周六','周日'],
						'dayNamesMin'   : ['日','一','二','三','四','五','六']
					});

					self.ajaxLoader = new Z.AjaxLoader({
						url : Z.url('/backend/node/records'),
						data: {
							pageSize : 8
						},
						templates : {
							list : self.templates.list,
							none : '',
							methods : {
								substr : function(string,length){
									return Z.substr((string||''), 0, length);
								},
								thumbnail : function(name){
									return Z.url('/assets/upload/img/'+Z.thumbnailName(name, '150_150'));
								}
							}
						},
						containers : {
							list : dialog.find('ul.records'),
							pagination : dialog.find('div.pagination')
						},
						after : function(data){
							Z.alignImage(dialog.find('ul.records span.image-container img'), 150, 150);

							self.fillParents(data);

							self.dialog.find('ul.records li[type="1"] a').click(function(e){
								self.parent = $(this).parent().attr('data');
								self.ajaxLoader.request({
									'parent' : self.parent
								});
								return false;
							});

							self.dialog.find('ul.records li[type="2"] a').click(function(e){
								if(!e.ctrlKey){
									var active = $(this).parent().siblings('.active');
									if(active.length > 0){
										active.removeClass('active');
									}
								}

								$(this).parent().toggleClass('active');

								return false;
							});

							self.dialog.find('ul.parents a').click(function(){
								self.parent = $(this).attr('data');
								self.ajaxLoader.request({
									'parent' : self.parent
								});
								return false;
							});
						}
					});

					self.ajaxLoader.request();

					dialog.find('form.filter').submit(function(){
						self.filter($(this),dialog);
						return false;
					});

					dialog.find('ul.button a.submit').click(function(){
						self.submit(dialog);
						return false;
					});

					dialog.find('ul.button a.add-image').live('click',function(){
						ImageBrowser.uploadDialog = Z.form({
							'title' : '添加图片',
							'width' : 500,
							'content' : $.tmpl(self.templates.uploadForm,{
								'parent':self.parent,
								'sizes' : '150_150', 
								'callback':'Z.ImageBrowser.uploadBack'
							})
						});
						return false;
					});
				}
			});
		},
		'selectImage' : function(target,event){
			var li  = $(target).parent(),
			active = $(li).siblings('.active'),
			image = {
				'id' : $(target).attr('data'), 
				'src' : $(target).children('img').attr('src'),
				'alt' : $(target).children('img').attr('alt')
			};

			if(this.type == ImageBrowser.MULTIPLE){
				if(event.ctrlKey){
					$(li).toggleClass('active');
				}else{
					if($(active).length > 0){
						$(active).removeClass('active');
					}
					$(li).addClass('active');
				}
			}

			if(this.type == ImageBrowser.SINGLE){
				if($(active).length > 0){
					$(active).removeClass('active');
				}
				$(li).addClass('active');
				this.image = image;
			}
		},
		'submit' : function(dialog){
			var self = this;

			switch(this.type){
				case ImageBrowser.MULTIPLE:
					var lis = dialog.find('ul.records li.active');
					if(lis.length == 0){
						Z.alert('请选择图片');
						return;
					}else{
						var ids = [],
						tds = [],
						val = $(this.target).val(),
						html = $(this.target).next().find('tr').html();

						if(val != ''){
							ids.push(val);
						}

						if(html != ''){
							tds.push(html);
						}

						$(lis).each(function(){
							var image = $(this).find('span.image-container > img'),
							id = $(this).attr('data');
							if($.inArray(id,val.split(',')) == -1){
								ids.push(id);
								tds.push('<td><div><img src="'+image.attr('src')+'" alt="'+image.attr('alt')+'"/><a href="javascript:void(0);" data="'+id+'">X</a></div></td>');
							}
						});

						$(this.target).val(ids.join(','));
						$(this.target).next().find('tr').html(tds.join(''));

						$(this.target).next().find('td > div > a').click(function(event){
							var valArray = $(self.target).val().split(','),
							id = $(this).attr('data'),
							index = $.inArray(id,valArray);

							$(self.target).val(valArray.del(index).join(','));

							$(this).parent().remove();
							event.stopPropagation();
						});
					}
					break;
				case ImageBrowser.SINGLE:
					var li = dialog.find('ul.records li.active:eq(0)');

					if(li.length == 0){
						Z.alert('请选择图片');
						return;
					}

					$(this.target).val($(li).attr('data'));
					$(this.target).next().find('div').html('');
					$(this.target).next().find('div').append($(li).find('span.image-container > img'));
					break;
			}

			dialog.close();
		},
		'filter' : function(form){
			var self = this;

			self.ajaxLoader.request({
				'label' : $(form).find('input[name=name]').val(),
				'start' : $(form).find('input[name=start]').val(),
				'end' : $(form).find('input[name=end]').val(),
				'parent' : -1
			});
		},
		'fillParents' : function(data){
			var parentHtml = [];
			$(data.parents).each(function(i,item){
				if(i > 0){
					parentHtml.push('<li>/</li>');
				}
				parentHtml.push('<li><a href="javascript:void(0);" data="'+item.id+'">'+item.name+'</a></li>');
			});
			this.dialog.find('ul.parents').html(parentHtml.join(''));
		}
	};

	window.Z.ImageBrowser = ImageBrowser;
})(window);